package com.android.kotlincoroutinemvvmdemo.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.android.kotlincoroutinemvvmdemo.R

/*
* 风车view
* */
class WindmillView @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
) : View(context, attributeSet) {

    private var mWidth = 0
    private var mHeight = 0

    private val degreeArr = floatArrayOf(90F, 180F, 270F, 360F)

    private val mPaint0 by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            //拐角---(尖角)
            strokeJoin = Paint.Join.MITER
            color = context.resources.getColor(R.color.color_da8989)
            style = Paint.Style.FILL
        }
    }

    private val mPath by lazy {
        Path()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        Log.d(TAG, "override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)")
        mWidth = when(MeasureSpec.getMode(widthMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(widthMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_60).toInt()
            }
        } - paddingStart - paddingEnd

        mHeight = when(MeasureSpec.getMode(heightMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                MeasureSpec.getSize(heightMeasureSpec)
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_60).toInt()
            }
        } - paddingTop - paddingBottom

        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        Log.d(TAG, "override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int)")
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        setBackgroundColor(context.resources.getColor(R.color.color_F3F3F3))
        canvas?.apply {
            translate(mWidth / 2.0F, mHeight / 2.0F)
            for (degree in degreeArr) {
                save()
                rotate(degree)
                mPath.apply {
                    moveTo(0F, 0F)
                    quadTo(mWidth / 5.0F, -mHeight / 3.0F, mWidth * 2.0F / 5.0F, 0F)
                    close()
                }
                drawPath(mPath, mPaint0)
                restore()
            }
        }
    }

    companion object {
        const val TAG = "WindmillView"
    }
}